﻿/*  CLR版本: 4.0.30319.18063
 * 系统时间: 2014/10/31 14:20:43
 * 创建年份: 2014
 *     作者: 程炜.Snail
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;

namespace Quick.Communicator
{
    /// <summary>
    /// I/O 缓冲区
    /// </summary>
    public class BufferManager
    {
        int m_NumBytes; 
        byte[] m_Buffer;
        Stack<int> m_FreeIndexPool;
        int m_CurrentIndex;
        int m_BufferSize;

        public BufferManager(int totalBytes, int bufferSize)
        {
            m_NumBytes = totalBytes;
            m_CurrentIndex = 0;
            m_BufferSize = bufferSize;
            m_FreeIndexPool = new Stack<int>();
        }

        /// <summary>
        /// 初始化缓冲区
        /// </summary>
        public void InitBuffer()
        {
            m_Buffer = new byte[m_NumBytes];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool SetBuffer(SocketAsyncEventArgs args)
        {

            if (m_FreeIndexPool.Count > 0)
            {
                args.SetBuffer(m_Buffer, m_FreeIndexPool.Pop(), m_BufferSize);
            }
            else
            {
                if ((m_NumBytes - m_BufferSize) < m_CurrentIndex)
                {
                    return false;
                }
                args.SetBuffer(m_Buffer, m_CurrentIndex, m_BufferSize);
                m_CurrentIndex += m_BufferSize;
            }
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        public void FreeBuffer(SocketAsyncEventArgs args)
        {
            m_FreeIndexPool.Push(args.Offset);
            args.SetBuffer(null, 0, 0);
        }


    }
}
